<?php
namespace YDCMS\controllers;

use YDCMS\core\Controller;
use YDCMS\models\User;

class AuthController extends Controller
{
    private $user;

    public function __construct()
    {
        parent::__construct();
        $this->user = new User();
    }

    public function login()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';

            $user = $this->user->findByEmail($email);

            if ($user && $this->user->verifyPassword($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_role'] = $user['role'];
                
                return $this->redirect('/admin/dashboard');
            }

            return $this->view('auth/login', [
                'error' => 'Invalid email or password'
            ]);
        }

        return $this->view('auth/login');
    }

    public function register()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'] ?? '';
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';

            if ($password !== $confirmPassword) {
                return $this->view('auth/register', [
                    'error' => 'Passwords do not match'
                ]);
            }

            if ($this->user->findByEmail($email)) {
                return $this->view('auth/register', [
                    'error' => 'Email already exists'
                ]);
            }

            if ($this->user->create($username, $email, $password)) {
                return $this->redirect('/auth/login');
            }

            return $this->view('auth/register', [
                'error' => 'Registration failed'
            ]);
        }

        return $this->view('auth/register');
    }

    public function logout()
    {
        session_destroy();
        return $this->redirect('/auth/login');
    }
} 